package com.imax.center.utils;

import lombok.extern.slf4j.Slf4j;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class TcpDataUtil {

    public static Map<String, Object> parseData(String input) {
        try {
            Map<String, Object> result = new HashMap<>();

            // Parse Header
            result.put("Header", input.substring(0, 2));

            // Parse DataLength
            result.put("DataLength", input.substring(2, 6));

            // Parse QN, ST, CN, PW, MN, Flag
            int cpIndex = input.indexOf("CP=");
            String dataPart = input.substring(6, cpIndex + 2);
            String[] keyValuePairs = dataPart.split(";");

            for (String pair : keyValuePairs) {
                String[] kv = pair.split("=");
                if (kv.length == 2) {
                    result.put(kv[0], kv[1]);
                }
            }

            // Parse CP field
            int firstAmpersand = input.indexOf("&&");
            int lastAmpersand = input.lastIndexOf("&&");
            String cpPart = input.substring(firstAmpersand + 2, lastAmpersand);
            String[] cpKeyValuePairs = cpPart.split(";");
            Map<String, Object> cpMap = new HashMap<>();

            for (String pair : cpKeyValuePairs) {
                // Further parse wxxxx-xxx key-value pairs
                String[] subPairs = pair.split(",");
                for (String subPair : subPairs) {
                    String[] kv = subPair.split("=");
                    if (kv.length == 2) {
                        try {
                            cpMap.put(kv[0], Double.parseDouble(kv[1]));
                        } catch (NumberFormatException e) {
                            cpMap.put(kv[0], kv[1]);
                        }
                    }
                }
            }

            //将CP中的DataTime字段转为字符串
            if (cpMap.containsKey("DataTime")) {
                double number = Double.parseDouble(cpMap.get("DataTime").toString());
                DecimalFormat df = new DecimalFormat("0");
                String DataTimeStr = df.format(number);
                cpMap.put("DataTime", DataTimeStr);
            }
            //将CP中的AlarmTime字段转为字符串
            if (cpMap.containsKey("AlarmTime")) {
                double number = Double.parseDouble(cpMap.get("AlarmTime").toString());
                DecimalFormat df = new DecimalFormat("0");
                String AlarmTimeStr = df.format(number);
                cpMap.put("AlarmTime", AlarmTimeStr);
            }

            result.put("CP", cpMap);

            // Parse CRC16
            result.put("CRC16", input.substring(lastAmpersand + 2));

            return result;
        } catch (Exception e) {
            log.error("parseData error", e);
            return null;
        }
    }

}
